//
//  HD_NKM_MapView+Download.m
//  HDWuDaDaoServiceCenter
//
//  Created by HDNiuKuiming on 2017/5/20.
//  Copyright © 2017年 HDNiuKuiming. All rights reserved.
//

#import "HD_NKM_MapView+Download.h"

@implementation HD_NKM_MapView (Download)

- (void)recordItemToSet:(NSString *)suffixPath
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.mapItemSet addObject:suffixPath];
    });
}

- (void)startDownloadItem
{
    [self downloadMapItemForNot250];
}

- (void)downloadFirstLevel
{
    NSArray *pathArray = @[@"1_250_0_0.png",
                           @"1_250_0_1.png",
                           @"1_250_0_2.png",
                           @"1_250_0_3.png",
                           @"1_250_1_0.png",
                           @"1_250_1_1.png",
                           @"1_250_1_2.png",
                           @"1_250_1_3.png",
                           @"1_250_2_0.png",
                           @"1_250_2_1.png",
                           @"1_250_2_2.png",
                           @"1_250_2_3.png",
                           @"1_250_3_0.png",
                           @"1_250_3_1.png",
                           @"1_250_3_2.png",
                           @"1_250_3_3.png"];
    
    for (NSInteger i=0;i<pathArray.count;i++) {
//        NSString *str = [NSString stringWithFormat:@"%@%@", self.urlPrefix,pathArray[i]];
        NSString *str = [NSString stringWithFormat:@"%@",pathArray[i]];
        [self.mapItemSet addObject:str];
    }
    [self downloadMapItemForNot250];
}

#pragma mark
#pragma mark -------- 瓦片地图背地里下载 ---------


- (void)downloadMapItemForNot250
{
    if (self.downloadItemQueue == nil || self.mapItemSet.count == 0)
        self.downloadItemQueue = [[NSOperationQueue alloc]init];
    
    NSEnumerator *enumerator = [self.mapItemSet objectEnumerator];
    
    NSString *path  = [enumerator nextObject];
    NSMutableArray *array = [NSMutableArray new];
    while (path != nil) {
        NSString *pathStr = [NSString stringWithFormat:@"%@%@", self.urlPrefix, path];
        [array addObject:pathStr];
        path = [enumerator nextObject];
    }
    [self.mapItemSet removeAllObjects];
    
    for(NSString *itemPath in array){
//        NSLog(@"%@",itemPath);
        NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self
                                                                               selector:@selector(downloadImage:)
                                                                                 object:itemPath];
        
        [self.downloadItemQueue addOperation:operation];
    }
    
    [self.downloadItemQueue setMaxConcurrentOperationCount:5];
}


-(void)downloadImage:(NSString *)url {
    
    NSString *imgName = [url substringFromIndex:self.urlPrefix.length];
    NSString *nowItemPath = [NSString stringWithFormat:@"%@/%@", self.mapItemPath,imgName];
    NSFileManager *fManager  = [NSFileManager defaultManager];
    NSDictionary *attr = [fManager attributesOfItemAtPath:nowItemPath error:nil];
    NSInteger fileSize = [attr[NSFileSize] integerValue];
    if ([fManager fileExistsAtPath:nowItemPath] && fileSize>0)
        return;
    
    NSURL *URL = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];//下载请求
    
    NSString *pathTemp = [NSString stringWithFormat:@"%@/Resource/WebMap/%@_%@_data", kCachePath, self.floorStr,imgName];
    if ([fManager fileExistsAtPath:pathTemp]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSError *errror = nil;
            [fManager removeItemAtPath:pathTemp error:&errror];
        });
    }
    
    NSURLSessionDownloadTask *downTask = nil;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 下载的过程
    downTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress){}  destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        // 告诉服务器下载的文本保存的位置在那里
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
//        NSLog(@"file = %@",targetPath);
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
//        NSLog(@"response = %@,filePath = %@",response,filePath);
        
        if (filePath != nil) // 中途取消下载的话，会为nil
        {
            NSData *data = [[NSData alloc]initWithContentsOfURL:filePath];
            UIImage * image = [[UIImage alloc]initWithData:data];
            
            [self storeImg:image withName:imgName];
            [fManager removeItemAtPath:[filePath path] error:nil];
            [self reloadViewAction];
        }
        else {
            LOG(@"瓦片地图下载失败！！！");
        }
    }];
    [downTask resume];
}

- (void)storeImg:(UIImage *)img
        withName:(NSString *)imgName
{
    BOOL isDir = FALSE;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:self.mapItemPath isDirectory:&isDir] == NO)
    { [[HDDeclare sharedDeclare] createMapPath:self.mapItemPath]; }
    
    BOOL isDirExist = [fileManager fileExistsAtPath:self.mapItemPath isDirectory:&isDir];
    if (isDirExist == YES) {
        
        NSString *storeImgPath = [NSString stringWithFormat:@"%@/%@", self.mapItemPath, imgName];
        NSData *imagedata=UIImagePNGRepresentation(img);
        if ([fileManager fileExistsAtPath:storeImgPath]) // 如果多线程冲突的话，可能会有下载失败的情况
            [fileManager removeItemAtPath:storeImgPath error:nil];
        
        [fileManager createFileAtPath:storeImgPath contents:imagedata attributes:nil];
    }
}


@end
